import asyncio

from langchain_mcp_adapters.client import MultiServerMCPClient
from langgraph.prebuilt import create_react_agent

from agent.my_llm import llm

# Python MCP 服务端的连接配置
python_mcp_server_config = {
    # 'url': 'http://127.0.0.1:8080/streamable',
    # 'transport': 'streamable_http',
    'url': 'http://127.0.0.1:8080/sse',
    'transport': 'sse',
}


mcp_client = MultiServerMCPClient(
    {
        'python_mcp': python_mcp_server_config
    }
)


async def create_agent():
    """必须是异步函数"""
    mcp_tools = await mcp_client.get_tools()
    print(mcp_tools)

    # 查询mcp服务端定义的prompt
    p = await mcp_client.get_prompt(server_name='python_mcp', prompt_name='ask_about_topic', arguments={'topic': '大模型开发'})
    print(p)

    # 查询mcp服务端定义的resource
    data = await mcp_client.get_resources(server_name='python_mcp', uris='resource://config')
    print(data)     # [Blob 2041768728992]
    print(type(data))   # <class 'list'>
    if isinstance(data, list) and data:
        print(data[0])
        # metadata={'uri': 'resource://config'} data='{"theme":"dark","version":"1.2.0","features":["tools",
        # "resources"]}' mimetype='text/plain'
        print(data[0].data)
        # {"theme":"dark","version":"1.2.0","features":["tools","resources"]}

    return create_react_agent(
        llm,
        tools=mcp_tools,
        prompt='你是一个智能助手，尽可能的调用工具回答用户的问题'
    )


agent = asyncio.run(create_agent())

